package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * str
 * 794. 有效的井字游戏
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/9 9:22
 */
public class ValidTicTacToe {

    public static void main(String[] args) {
        ValidTicTacToe test = new ValidTicTacToe();
        String[] arr = {"XXX", "OOX", "OOX"};
        boolean b = test.validTicTacToe(arr);
        System.out.println(b);
    }


    private int[][] item = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};

    public boolean validTicTacToe(String[] board) {
        char[] arr = new char[9];
        int n = 0;
        for (String s : board) {
            for (int i = 0; i < 3; i++) {
                arr[n++] = s.charAt(i);
            }
        }
        int c1 = count(arr, 'X');
        int c2 = count(arr, 'O');
        if (c1 < c2 || c1 > c2 + 1) {
            return false;
        }
        boolean a = find(arr, 'X');
        boolean b = find(arr, 'O');
        return (!a || c1 != c2) && (!b || c1 == c2);
    }

    private int count(char[] arr, char c) {
        int count = 0;
        for (char c1 : arr) {
            if (c1 == c) {
                count++;
            }
        }
        return count;
    }

    private boolean find(char[] arr, char c) {
        for (int[] ints : item) {
            if (c == arr[ints[0]] && arr[ints[0]] == arr[ints[1]] && arr[ints[1]] == arr[ints[2]]) {
                return true;
            }
        }
        return false;
    }

}
